<template>
    <div class="orderfile-uploader-container">
        <van-uploader
            ref="orderfileUploader"
            class="attach-file-upload"
            v-model="uploadstate.pictureFileList"
            :after-read="afterRead"
            :before-read="beforeRead"
            @delete="removePicture"
            :max-count="imgmaxcount"
            result-type="file"
            multiple>
            <div class="van-uploader__upload">
                <wp-icon
                    :style="{color:'#636363'}"
                    name="camera"
                    size="28"/>
                <span class="van-uploader__upload-text">{{$st('wp_upload_image')}}</span>
            </div>
        </van-uploader>
        <van-uploader
            class="attach-document-upload"
            :after-read="afterReadDocument"
            :before-read="beforeReadDocument"
            accept="*/*"
            result-type="file"
            multiple>
            <div class="van-uploader__upload">
                <wp-icon
                    :style="{color:'#636363'}"
                    name="enclosure"
                    size="28"/>
                <span class="van-uploader__upload-text">{{ $st('wp-shang-chuan-wen-jian') }}</span>
            </div>
        </van-uploader>
    </div>
    <div
        class="content-attach-item"
    >
        <div
            class="content-item-label"
            v-if="uploadstate.documentFileList&&uploadstate.documentFileList.length>0">{{$st('attachment')}}</div>
        <div>
            <file-bar
                class="filebar"
                :file="file.data || file"
                v-for="(file, index) in uploadstate.documentFileList"
                :key="index"
            >
                <template #button>
                    <a
                        :href="file.fileurl"
                        @click.prevent="removeDocumentFile(file)"
                        style="color:black"><van-icon
                            name="close"
                            size="20"/></a>
                </template>
            </file-bar>
        </div>
    </div>
</template>
<script>
// import AttachFileUploader from '@/components/_common/AttachFileUploader.vue';
import FileBar from '@/components/_common/FileBar.vue';
import { useAttachmentFile } from '@/setup/repair/AttachmentFile.js';
import { computed, toRef } from 'vue';
import { selfI18n } from '@/i18n';
import { apiService } from '@/api/apiService.js';
import { capiCommonFile } from '@/api/server.js';
import { Toast } from 'vant';

export default {
    components: { FileBar },
    props: {
        attachments: Array,
        imgmaxcount: {
            type: Number,
            default () {

            }
        },
        docmaxcount: Number
    },
    setup (props, context) {
        const attachments = toRef(props, 'attachments');
        const equalFileImage = (item) => {
            let itemtype, filetext;
            if (item.filename !== undefined) {
                // 旧数据
                item.status = '';

                item.message = '';
                itemtype = item.filename.lastIndexOf('.');
                filetext = item.filename.substring(itemtype + 1);
            } else {
                // 新上传
                itemtype = item.file.name.lastIndexOf('.');
                filetext = item.file.name.substring(itemtype + 1);
            }
            // 上传图片支持格式
            const imgtype = ['jpg', 'png'];
            var isimg = imgtype.indexOf(filetext);
            return isimg >= 0;
        };
        const formatPictureAttachs = (val) => {
            if (val === [] || val === undefined) {
                return [];
            } else {
                const newarr = val.filter(function (item) {
                    return equalFileImage(item);
                });
                return newarr.map((item) => {
                    item.url = item.fileurl;
                    return item;
                });
            }
        };
        const formatDocumentAttachs = (val) => {
            if (val === [] || val === undefined) {
                return [];
            } else {
                const newarr = val.filter(function (item) {
                    return !equalFileImage(item);
                });
                return newarr;
            }
        };
        const uploadstate = computed({
            get: () => {
                const count = attachments.value;
                return {
                    pictureFileList: formatPictureAttachs(count),
                    documentFileList: formatDocumentAttachs(count)
                };
            },
            set: (value) => {
                const tmp = value.pictureFileList.concat(value.documentFileList).map(child => {
                    return child.data || child;
                });
                context.emit('update:attachments', tmp);
            }

        });

        const postUploadAttach = (file, callback) => {
            const formdata = new FormData();
            formdata.append('bucketname', 'ncmaintain');
            formdata.append('filename', file.file.name);
            formdata.append('file', file.file);
            apiService({
                api: capiCommonFile,
                param: formdata,
                success: (data) => {
                    if (file instanceof Array) {
                        file.map((val, i) => {
                            val.data = data.value[i];
                            val.status = 'success';
                            val.url = data.value[i].fileurl;
                            val.message = selfI18n('wp_Uploaded_successfully');
                            // callback && callback();
                        });
                    } else {
                        file.data = data.value;
                        file.status = 'success';
                        file.url = data.value.fileurl;
                        file.message = selfI18n('wp_Uploaded_successfully');
                        // callback && callback();
                    };
                    callback && callback();
                },
                fail: data => {
                    file.status = 'failed';
                    file.message = selfI18n('wp_Upload_failed');
                },
                error: data => {
                    file.status = 'failed';
                    file.message = selfI18n('wp_Upload_failed');
                }
            });
        };
        const isNOArray = (file) => {
            const imgtype = ['jpg', 'png'];
            const itemtype = file.name.lastIndexOf('.');
            const fileext = file.name.substring(itemtype + 1);
            const isimg = imgtype.indexOf(fileext);
            if (isimg < 0) {
                Toast(selfI18n('wp_Uploading_pictures_only_supports_JPG_and_PNG'));
                return false;
            } else if (file.size > 10485760) {
                Toast(selfI18n('wp_SizeOf_Uploading_Picture_ShallNot_Exceed_10MB'));
                return false;
            } else {
                return true;
            }
        };
        const beforeRead = (file) => {
            // 上传图片支持格式;
            // console.log(Array.isArray(file));
            // const imgtype = ['jpg', 'png'];
            // const itemtype = file.name.lastIndexOf('.');
            // const fileext = file.name.substring(itemtype + 1);
            // const isimg = imgtype.indexOf(fileext);
            // if (isimg < 0) {
            //     Toast(selfI18n('wp_Uploading_pictures_only_supports_JPG_and_PNG'));
            //     return false;
            // } else if (file.size > 10485760) {
            //     Toast(selfI18n('wp_SizeOf_Uploading_Picture_ShallNot_Exceed_10MB'));
            //     return false;
            // } else {
            //     return true;
            // }
            // 判断是否是多个上传 ，多个的话为Array
            if (Array.isArray(file)) {
                // file.forEach((item) => {
                //     return isNOArray(item);
                // });
                // return true;
                // 遍历file是否都符合条件，有一条不符则提示错误
                const bool = file.every(function (item, index) {
                    return isNOArray(item);
                });
                return bool;
            } else {
                return isNOArray(file);
            };
            // return true;
        };
        const beforeReadDocument = (file) => {
            const itemtype = file.name.lastIndexOf('.');
            const fileext = file.name.substring(itemtype + 1);
            const imgtype = ['jpg', 'png'];
            const isimg = imgtype.indexOf(fileext);
            if (isimg >= 0) {
                Toast(selfI18n('wp_Uploading_file_not_supports_JPG_and_PNG'));
                return false;
            } else if (file.size > 52428800) {
                Toast(selfI18n('wp_SizeOf_Uploading_file_ShallNot_Exceed_50MB'));
                return false;
            } else {
                return true;
            }
        };
        // const refreshdata = () => {
        //     formatPictureAttachs(props.attachments);
        //     formatDocumentAttachs(props.attachments);
        // };
        const updatePictureOrFile = () => {
            uploadstate.value = {
                ...uploadstate.value
            };
        };

        const { removeFile } = useAttachmentFile();
        const removeDocumentFile = (file) => {
            const params = file.data || file;
            removeFile(params, () => {
                const index = (uploadstate.value.documentFileList || []).findIndex((child) => child === file);
                uploadstate.value.documentFileList.splice(index, 1);
                updatePictureOrFile();
            });
        };
        const removePicture = (file) => {
            const params = file.data || file;
            removeFile(params, () => {
                updatePictureOrFile();
            });
        };
        return {
            uploadstate,
            updatePictureOrFile,
            removeDocumentFile,
            removePicture,
            postUploadAttach,
            beforeRead,
            beforeReadDocument,
            isNOArray,
            formatPictureAttachs,
            formatDocumentAttachs
            // refreshdata
        };
    },
    // watch: {
    //     attachments () {
    //         this.refreshdata();
    //     }
    // },
    methods: {
        // initdata () {
        //     this.formatPictureAttachs(this.attachments);
        //     this.formatDocumentAttachs(this.attachments);
        // },
        afterRead (file) {
            // console.log(file);
            // file.status = 'uploading';
            // file.message = this.$st('wp_Uploading_ellipsis');

            // this.postUploadAttach(file, async () => {
            //     await this.$nextTick();

            //     file.status = 'done';
            //     file.message = '';
            // });
            // var reader = new FileReader();
            // reader.addEventListener('load', function () {
            //     file.content = reader.result;
            // }, false);
            // if (file && file.file) {
            //     reader.readAsDataURL(file.file);
            // }
            if (file instanceof Array) {
                file.map((val) => {
                    this.checkafterread(val);
                    // if (this.isNOArray(file)) {
                    //     this.checkafterread(val);
                    // } else {
                    //     return false;
                    // }
                });
            } else {
                this.checkafterread(file);
            }
        },
        checkafterread (val) {
            val.status = 'uploading';
            val.message = this.$st('wp_Uploading_ellipsis');

            this.postUploadAttach(val, async () => {
                await this.$nextTick();

                val.status = 'done';
                val.message = '';
                this.updatePictureOrFile();
            });
            var reader = new FileReader();
            reader.addEventListener('load', () => {
                val.content = reader.result;
            }, false);
            if (val && val.file) {
                reader.readAsDataURL(val.file);
            }
        },
        afterReadDocument (file) {
            this.postUploadAttach(file, async () => {
                await this.$nextTick();
                this.uploadstate.documentFileList.push(file);
                this.updatePictureOrFile();
            });
        }
    }
};
</script>
<style lang="scss">
.orderfile-uploader-container{
    display: inline-flex;
    flex-wrap: wrap;
    text-align: left;
    margin-left:5px;
    // margin-right: 15px;
    // margin-top: 10px;
    // margin-bottom: 10px;
    //文件上传样式
    .attach-file-upload{
        background: #f5f5f5;
        // margin-bottom: 10px;
        margin: 10px 4px 10px 10px;
        // padding: 10px;
        box-sizing: border-box;
        .van-uploader__upload{
            margin: 0px;

        }

    }
    .attach-document-upload{
        // padding:15px 10px 10px 10px;
        background: #f5f5f5;
        margin: 10px 0px 10px 4px;
        // padding: 10px;
        box-sizing: border-box;
        .van-uploader__upload{
            margin: 0px;

        }
    }

    .van-uploader__input{
        width: 50%;
    }
    .van-uploader__input-wrapper{
        display: flex;
    }
}
.content-attach-item {
    padding-top: 5px;
    padding-bottom: 5px;
    //margin-left: 15px;
}
.content-item-label {
  text-align: left;
  min-width: 100px;
  width: 20%;
  color: rgba(0, 0, 0, 0.6);
  padding: 3px;
}
.filebar {
  margin-top: 5px;
  margin-bottom: 5px;
}
</style>
